<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="7"
              :sm="16">
              <a-form-item label="公司名称">
                <a-input
                  v-model="queryParam.companyName"
                  placeholder="请输入公司名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="7"
              :sm="16">
              <a-form-item label="公司经营范围">
                <a-input
                  :style="{ width: '100%'}"
                  v-model="queryParam.businessScope"
                  placeholder="请输入公司经营范围" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="客户等级">
                <a-select
                  :style="{ width: '100%'}"
                  v-model="queryParam.customerGrade"
                  placeholder="请选择客户等级"
                  default-value="0">
                  <a-select-option value="1">优质客户</a-select-option>
                  <a-select-option value="2">普通客户</a-select-option>
                  <a-select-option value="3">黑名单客户</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="4"
              :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="searchCustom">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="addCustom">新建</a-button>
      </div>
      <div>
        <s-table
          ref="table"
          size="default"
          rowKey="customerId"
          :columns="columns"
          :data="loadData"
          showPagination="auto"
          :customRow="tableCustomRow">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="level"
            slot-scope="text, record">
            {{ ['','优质客户','普通客户','黑名单客户'][record.customerGrade] }}
          </span>
          <span
            slot="description"
            slot-scope="text">
            <ellipsis
              :length="4"
              tooltip>{{ text }}</ellipsis>
          </span>

          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a
                v-if="update"
                @click="handleEditCustom(record)">配置</a>
              <a-divider type="vertical" />
              <a
                v-if="deleteBtn"
                @click="handleDeleteCustom(record)">删除</a>
            </template>
          </span>
        </s-table>
      </div>
      <div
        style="margin-top: 30px"
        v-show="custom">
        <div class="table-operator">
          <span style="font-size: 20px;font-weight: bold;padding: 10px;padding-right: 30px">联系人</span>
          <a-button
            type="primary"
            icon="plus"
            @click="addContact">新建</a-button>
          <a-spin :spinning="contactTabLoading">
            <a-table
              ref="contactTable"
              size="default"
              rowKey="contactId"
              :columns="contactColumns"
              :dataSource="contacts || []"
              :customRow="tableCustomRowContact"
              :pagination="false">
              <span
                slot="serial"
                slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span
                slot="action"
                slot-scope="text, record">
                <template>
                  <a @click="handleEditContact(record)">配置</a>
                  <a-divider type="vertical" />
                  <a @click="handleDeteleContact(record)">删除</a>
                </template>
              </span>
            </a-table>
          </a-spin>
        </div>
      </div>

      <custom-create-form
        ref="customCreatForm"
        :visible="customCreateVisible"
        :loading="customLoading"
        :model="custom"
        @cancel="handleCancel"
        @ok="customCreateOK" />
      <custom-edit-form
        ref="customEditForm"
        :visible="customEditVisible"
        :loading="customLoading"
        :model="custom"
        @cancel="handleCancel"
        @ok="customEditOK" />
      <contact-create-form
        ref="contactCreateForm"
        :visible="contactCreateVisible"
        :loading="contactLoading"
        :model="contact"
        @cancel="handleCancel"
        @ok="contactCreateOK" />
      <contact-edit-form
        ref="contactEditForm"
        :visible="contactEditVisible"
        :loading="contactLoading"
        :model="contact"
        @cancel="handleCancel"
        @ok="contactEditOK" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import {
  getCustomList,
  updateContact,
  saveContact,
  deleteContact,
  saveCustom,
  getContact,
  deleteCustom,
  updateCustom
} from '@/api/manage'

import CustomCreateForm from './modules/CustomCreateForm'
// import ContactCreateForm from './modules/ContactCreateForm'
import ContactCreateForm from '../supplier/modules/ContactCreateForm'
import CustomEditForm from './modules/CustomEditForm'
import ContactEditForm from '../supplier/modules/ContactEditForm'
import { columns, contactColumns } from './config'
import { message, Modal } from 'ant-design-vue'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CustomCreateForm,
    ContactCreateForm,
    CustomEditForm,
    ContactEditForm
  },
  data () {
    this.columns = columns
    this.contactColumns = contactColumns
    return {
      // 权限参数
      info: false, // 查看联系人
      list: false, // 列表
      save: false, // 家
      select: false, // 查所有 基本没有
      deleteBtn: false, // 删
      update: false, // 改
      // 联系人
      contactInfo: false, // 查看联系人
      contactList: false, // 列表
      contactSave: false, // 家
      contactSelect: false, // 查所有 基本没有
      contactDeleteBtn: false, // 删
      contactUpdate: false, // 改
      // create model
      customCreateVisible: false,
      customEditVisible: false,
      contactCreateVisible: false,
      contactEditVisible: false,

      customLoading: false,
      contactLoading: false,

      custom: undefined,
      contact: undefined,
      contactTabLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      // customSelect: undefined,
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize, ...this.queryParam }
        return (
          this.list &&
          getCustomList(requestParameters).then(res => {
            return Object.assign({}, res, {
              totalCount: res.total,
              pageNo: parameter.pageNo,
              pageSize: parameter.pageSize
            })
          })
        )
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null,
      contactId: null,
      contacts: []
    }
  },
  created () {
    // 点击查看客户
    this.list =
      isInMenu(this.menu, 'ROLE_but:customer:list') &&
      isInMenu(this.menu, 'ROLE_but:customer:info') &&
      isInMenu(this.menu, 'ROLE_but:contact:info') &&
      isInMenu(this.menu, 'ROLE_but:contact:list')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:customer:save') && isInMenu(this.menu, 'ROLE_but:contact:save')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:contact:update') && isInMenu(this.menu, 'ROLE_but:customer:update')
    // 删除 but:customer:list,but:customer:info,but:contact:list,but:contact:info
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:customer:delete') && isInMenu(this.menu, 'ROLE_but:contact:delete')
  },
  mounted () {},
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    searchCustom () {
      this.$refs.table.refresh()
    },
    handleDeteleContact (record) {
      Modal.confirm({
        title: '删除联系人',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          deleteContact({ contactId: record.contactId }).then(() => {
            message.success('删除成功')
            this.contactTabLoading = true
            // 客户 type： 1 供应商： 2
            getContact({ relationId: this.custom.customerId, type: 1, page: 1, limit: 100 })
              .then(res => {
                this.contacts = res.data
              })
              .finally(() => {
                this.contactTabLoading = false
              })
          })
        }
      })
    },
    // 新增客户
    addCustom () {
      this.custom = null
      this.customCreateVisible = true
      const form = this.$refs.customCreatForm.form
      form.resetFields()
    },
    // 新增联系人
    addContact () {
      this.contact = null
      this.contactCreateVisible = true
    },
    // 删除客户
    handleDeleteCustom (record) {
      Modal.confirm({
        title: '删除客户信息',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          deleteCustom({ customerId: record.customerId }).then(() => {
            message.success('删除成功')
            this.$refs.table.refresh()
          })
        }
      })
    },
    // 编辑客户
    handleEditCustom (record) {
      this.custom = { ...record }
      this.customEditVisible = true
      const form = this.$refs.customEditForm.form
      // 清空表单
      form.resetFields()
      this.$nextTick(() => {
        form.setFieldsValue(this.custom)
      })
    },
    handleEditContact (reocrd) {
      this.contact = { ...reocrd }
      this.contactEditVisible = true
      const form = this.$refs.contactEditForm.form
      this.$nextTick(() => {
        form.setFieldsValue(this.contact)
      })
    },
    // 通过 ref 获取表格实例
    customCreateOK () {
      const form = this.$refs.customCreatForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          this.customLoading = true

          saveCustom(values)
            .then(() => {
              this.$refs.table.refresh()
              this.$message.info('新增成功')
              form.resetFields()
              this.customLoading = false
              this.customCreateVisible = false
            })
            .finally(() => {
              this.customLoading = false
            })
        }
      })
    },
    customEditOK () {
      const form = this.$refs.customEditForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          const param = Object.assign({}, values, {
            customerId: this.custom.customerId
          })
          updateCustom(param).then(() => {
            this.customLoading = false
            this.customEditVisible = false
            this.$message.info('配置修改成功')
            form.resetFields()
            this.$refs.table.refresh()
          })
        }
      })
    },
    contactCreateOK () {
      const form = this.$refs.contactCreateForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          saveContact(Object.assign({}, values, { type: 1, relationId: this.custom.customerId }))
            .then(() => {
              this.customLoading = false
              this.contactCreateVisible = false
              message.success('新增成功')
              this.contactTabLoading = true
              getContact({ relationId: this.custom.customerId, type: 1, page: 1, limit: 100 }).then(res => {
                this.contacts = res.data
                this.contactTabLoading = false
              })
            })
            .finally(() => {
              this.contactTabLoading = false
            })
        }
      })
    },
    contactEditOK () {
      const form = this.$refs.contactEditForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          this.contactLoading = true
          updateContact(
            Object.assign({}, values, { contactId: this.contact.contactId, type: 1, relationId: this.custom.customId })
          ).then(() => {
            this.contactEditVisible = false
            this.contactLoading = false
            message.success('配置成功')
            this.contactTabLoading = true
            getContact({ relationId: this.custom.customerId, type: 1, page: 1, limit: 100 }).then(res => {
              this.contacts = res.data
              this.contactTabLoading = false
            })
          })
        }
      })
    },
    handleCancel () {
      this.customCreateVisible = false
      this.customEditVisible = false
      this.contactCreateVisible = false
      this.contactEditVisible = false
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.customerId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.customerId
            this.custom = record
            this.contactTabLoading = true
            if (this.list) {
              // 客户 type： 1 供应商： 2
              getContact({ relationId: record.customerId, type: '1', page: 1, limit: 100 }).then(res => {
                this.contacts = res.data
                this.contactTabLoading = false
              })
            }
          }
        }
      }
    },
    tableCustomRowContact (record) {
      return {
        style: {
          'background-color': record.contactId === this.contactId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.contactId = record.contactId
          }
        }
      }
    }
  }
}
</script>
